<?php include("header.php") ?>
<style>
    .form-error {
        display: none;
    }
</style>
<section class="page container">
    <div class="row" style="padding-left: 0;padding-right: 0;">
        <div class="span4" style="margin-right: 0;">
            <h2 style="margin-top: 0px;">Solid Petro-Stock</h2>
        </div>
        <div class="span7" style="margin-left: 0;">
            <form id="reportFilter">
                <input id="dateFrom" name="dateFrom" type="text" class="datepicker" placeholder="Select From Date"
                       data-validation-format="dd-mm-yyyy" data-validation="date"
                       data-validation-error-msg="Please select To and From Date"/>
                <input id="dateTo" name="dateTo" type="text" class="datepicker" placeholder="Select To Date"
                       data-validation-format="dd-mm-yyyy" data-validation="date"
                       data-validation-error-msg="Please select To and From Date"/>
                <button style="margin-top: -7px;" id="submit-report" type="submit"
                        class="btn btn-box btn-primary ladda-button" data-style="slide-right"><i
                        class="icon-search"></i>
                </button>
            </form>
        </div>
        <div class="span5" style="text-align: right;margin-left: 0;margin-right: 0;">
            <a class="btn" href="<?php nav_url("petrostock/add") ?>" style="height:40px;"><h6><i
                        class="icon-edit icon-large"></i> &nbsp; Add New</h6></a>
            <button class="btn btn-success ladda-button" id="downloadreport"
                    data-style="expand-right" data-size="l">
                <h6><i class="icon-download-alt icon-large"></i> &nbsp;<span id="downloadMsg"> Download </span>
                </h6>
            </button>
            <a role="button" href="#myModal" class="btn btn-warning" data-toggle="modal">
                <h6><i class="icon-cog icon-large"></i> &nbsp;Grade
                </h6>
            </a>
        </div>
    </div>
    <hr style="margin-top: 0px;">
    <div class="row">
        <div class="span16">
            <table id="sample-table" class="table table-hover table-bordered tablesorter">
                <thead>
                <tr>
                    <th>Date</th>
                    <th>Grade</th>
                    <th>Opening Stock (Daily)</th>
                    <th>Purchase & Production (Add)</th>
                    <th>Sale & Consumption (Less)</th>
                    <th>Closing Stock</th>
                    <th class="td-actions">Action</th>
                </tr>
                </thead>
                <tbody id="tableData">
                </tbody>
            </table>
        </div>
    </div>
</section>
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Grade Management</h3>
    </div>
    <div class="modal-body">
        <form id="gradeForm" class="form-horizontal" style="padding-left: 10px;">
            <div class="control-group">
                <input type="hidden" id="gradeId" name="gradeId"/>
                <label class="control-label" style="padding-left: 0px;text-align: left;width:120px;">Grade <span
                        class="required">*</span></label>

                <div class="controls" style="margin-left: 0px;">
                    <input id="gradeName" name="gradeName" class="span3" type="text" data-validation="required"
                           data-validation-error-msg="Please enter Grade" placeholder="Grade">
                    <input id="gradeSubmitBtn" class="btn btn-primary ladda-button" data-style="slide-right"
                           type="submit" value="Save"/>
                </div>
            </div>
        </form>
        <div id="gradeData">
            <div class="spinner">
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    </div>
</div>
<?php include("footer.php") ?>
<script>
    $(document).ready(function () {
        $('#sample-table').tablesorter();
        $.get("<?php nav_url("petrostock/get") ?>", function (data) {
            formtable(data);
        });

        $.get("<?php nav_url("grade/get")?>", function (data) {
            populateGrade(data);
        })
    });


    function formtable(data) {
        var jsonData = JSON.parse(data);
        var tableBody = "";
        for (var i = 0; i < jsonData.length; i++) {
            tableBody += "<tr>";
            tableBody += "<td>" + moment(jsonData[i].date.date).format("DD-MMM-YYYY") + "</td>";
            tableBody += "<td>" + jsonData[i].grade.name + "</td>";
            tableBody += "<td>" + jsonData[i].openingStock + "</td>";
            tableBody += "<td>" + jsonData[i].purchaseAndProduction + "</td>";
            tableBody += "<td>" + jsonData[i].saleAndConsumption + "</td>";
            tableBody += "<td>" + jsonData[i].closingStock + "</td>";
            tableBody += "<td class='td-actions'>";
            tableBody += "<a href='<?php nav_url('petrostock/edit/') ?>" + jsonData[i].id + "' class='btn btn-small btn-info' tooltop='Edit'><i class='btn-icon-only icon-pencil'></i></a>";
            tableBody += "&nbsp;&nbsp;";
//            tableBody += "<a href='#' class='btn btn-small btn-danger' tooltop='Delete'><i class='btn-icon-only icon-remove'></i></a>";
            tableBody += "</td>";
            tableBody += "</tr>";
        }
        $("#tableData").html(tableBody);
    }

    $.validate({
        form: '#reportFilter',
        validateOnBlur: false,
        onError: function () {
            return false;
        },
        onSuccess: function ($form) {
            var submitButton = Ladda.create(document.querySelector('#submit-report'));
            $("#submit-report").attr("disabled", true);
            submitButton.start();
            var handler = $.post("<?php nav_url("petrostock/getDataForDates") ?>", $("#reportFilter").serialize(), function (data) {
                submitButton.stop();
                formtable(data);
                submitButton.stop();
                $("#submit-report").attr("disabled", false);
            })
                .error(function (error) {
                    console.log(error.responseText);
                    submitButton.stop();
                    $("#submit-report").attr("disabled", false);
                });

            return false;
        }
    });

    $("#downloadreport").click(function () {
        $("#downloadreport").attr("disabled", true);
        $("#downloadMsg").text("Please Wait..");

        var startDate = $("#dateFrom").val();
        var endDate = $("#dateTo").val();
        var fileDownloadUrl = "<?php nav_url('reportgenerator/generatespstock')?>";
        if (startDate != null && endDate != null) {
            fileDownloadUrl = "<?php nav_url('reportgenerator/generatespstock/')?>" + startDate + "/" + endDate;
        }
        $.fileDownload(fileDownloadUrl)
            .done(function () {
                $("#downloadreport").attr("disabled", false);
                $("#downloadMsg").text("Download");
            })
            .fail(function () {
                $("#downloadreport").attr("disabled", false);
                $("#downloadMsg").text("Download");
                alert("Please Contact Support. Some went wrong.!");
            });
        return false;
    });

    $.validate({
        form: '#gradeForm',
        validateOnBlur: false,
        onError: function () {
            return false;
        },
        onSuccess: function ($form) {
            var submitButton = Ladda.create(document.querySelector('#gradeSubmitBtn'));
            $("#gradeSubmitBtn").attr("disabled", true);
            submitButton.start();
            var handler = $.post("<?php nav_url("grade/addGrade") ?>", $("#gradeForm").serialize(), function (data) {
                $("#gradeName").val("");
                $("#gradeId").val("");
                populateGrade(data);
            })
                .always(function () {
                    submitButton.stop();
                    $("#gradeSubmitBtn").attr("disabled", false);

                })
                .error(function (error) {
                    console.log(error.responseText);
                });

            return false;
        }
    });

    function editGrade(gradeId) {
        $.get("<?php nav_url("grade/get/") ?>" + gradeId, function (data) {
            var json = JSON.parse(data);
            $("#gradeId").val(json.id);
            $("#gradeName").val(json.name);
        });
    }

    function deleteGrade(gradeId) {
        alert("Called" + gradeId);
        $.get("<?php nav_url("grade/delete/")?>" + gradeId, function (data) {
            populateGrade(data);
        });
    }

    function populateGrade(jsonArray) {
        var json = JSON.parse(jsonArray);
        var tableHeader = "<table class='table table-hover table-bordered tablesorter' style='width:100%'><thead><tr><th style='width:10%;'>Sr.no</th><th style='width:70%;'>Grade</th><th style='width:20%;'>Action</th></tr></thead>";
        var tableBody = "<tbody>";
        for (var i = 0; i < json.length; i++) {
            tableBody += "<tr><td>" + (i + 1) + "</td><td>" + json[i].name + "</td>";
            tableBody += "<td><a onClick='editGrade(" + json[i].id + ")' class='btn btn-small btn-info' tooltop='Edit'><i class='btn-icon-only icon-pencil'></i></a>&nbsp;&nbsp;";
            tableBody += "<a onClick='deleteGrade(" + json[i].id + ")' class='btn btn-small btn-danger' tooltop='Edit'><i class='btn-icon-only icon-remove'></i></a></td></tr>";
        }
        tableBody += "</tbody></table>";
        $("#gradeData").html(tableHeader + tableBody);
    }

</script>
</body>
</html>